package com.zhixi.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;
/**
 * @ClassName JWTUtil
 * @Author zhangzhixi
 * @Description jwt工具类
 * @Date 2022/8/18 16:42
 * @Version 1.0
 */
@SuppressWarnings("all")
@Component
public class JWTUtil {

    //密钥
    private static String secret;

    //过期时间（天）
    private static int expire;

    @Value("${emos.jwt.secret}")
    public void setSecret(String secret) {
        JWTUtil.secret = secret;
    }

    @Value("${emos.jwt.expire}")
    public void setExpire(int expire) {
        JWTUtil.expire = expire;
    }

    /**
     * 生成token
     */
    public static String createToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();

        //payload（存储的键值对）
        map.forEach(builder::withClaim);

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, expire);
        // 指定令牌的过期时间
        builder.withExpiresAt(instance.getTime());

        // JWT令牌
        return builder.sign(Algorithm.HMAC256(secret));
    }

    /**
     * 验证token+获取token中的 payload
     */
    public static DecodedJWT verify(String token) {
        //如果有任何验证异常，此处都会抛出异常
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        return decodedJWT;
    }
}